package com.lorenzogao.pley.ui.presenter


import com.lorenzogao.pley.bean.LoginBean
import com.lorenzogao.pley.common.Constant
import com.lorenzogao.pley.common.rx.RxHttpReponseCompat
import com.lorenzogao.pley.common.rx.subscriber.ErrorHandlerSubscriber
import com.lorenzogao.pley.common.rx.subscriber.RxBus
import com.lorenzogao.pley.common.util.ACache
import com.lorenzogao.pley.ui.presenter.contract.LoginContract
import io.reactivex.disposables.Disposable
import javax.inject.Inject

/**
 * 作者：Lorenzo Gao
 * Date: 2018/1/5
 * Time: 10:53
 * 邮箱：2508719070@qq.com
 * Description:
 */
class LoginPresenter @Inject constructor(mModel: LoginContract.ILoginModel, mView: LoginContract.LoginView) : BasePresenter<LoginContract.ILoginModel, LoginContract.LoginView>(mModel, mView) {


    fun login(phone: String, password: String) {


//        if (!VerificationUtils.matcherPhoneNum(phone)) {
//            mView!!.checkPhoneError()
//            return
//        }else {
//            mView!!.checkPhoneSuccess()
//        }
        mModel!!.login(phone, password).compose(RxHttpReponseCompat.compatResult()).subscribe(object : ErrorHandlerSubscriber<LoginBean>(mContext!!) {

            override fun onSubscribe(d: Disposable?) {

            }

            override fun onComplete() {
                mView!!.dimissLoading()
            }

            override fun onError(e: Throwable?) {
                super.onError(e)
                mView!!.dimissLoading()
            }

            override fun onNext(t: LoginBean?) {
                if (t != null) {
                    mView!!.LoginSuccess(t)
                    save(t)
                    RxBus.getDefault().post(t.user)
                }
            }
        })


    }


    private fun save(bean: LoginBean) {
        var mAChech = ACache.get(mContext)
        mAChech.put(Constant.TOKEN, bean.token)
        mAChech.put(Constant.USER, bean.user)


    }

}